//
//  JMSearchViewController.m
//  OpenSesame
//
//  Created by zhangjiaming on 16/1/4.
//  Copyright © 2016年 OpenSesame. All rights reserved.
//

#import "JMSearchViewController.h"
#import "JMSearchBar.h"
#import "JMBrandGroup.h"
#import "JMBrand.h"
#import "JMCar.h"
#import "JMSearchRecord.h"
#import "JMKeyInforController.h"

@interface JMSearchViewController () <UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) UITextField *searchbar;
@property (strong, nonatomic) NSArray *brandGroup; // 商标数组
@property (strong, nonatomic) NSMutableArray *allResult; // 存放将要搜索的所有搜索结果
@property (strong, nonatomic) NSArray *visibleResult; // 存放搜索出来的结果
@property (weak, nonatomic) UITableView *tableView;

@property (assign, nonatomic, getter=isSearch) BOOL search; // 是否为搜索状态,默认为0，显示历史搜索记录
@property (strong, nonatomic) NSArray *searchRecords; // 历史搜索结果

@end

@implementation JMSearchViewController
- (NSArray *)brandGroup {
    if (!_brandGroup) {
        _brandGroup = [JMBrandGroup brandGroupsList];
    }
    return _brandGroup;
}

- (NSMutableArray *)allResult {
    if (!_allResult) {
        _allResult = [NSMutableArray array];
    }
    return _allResult;
}

- (NSArray *)visibleResult {
    if (!_visibleResult) {
        _visibleResult = [NSArray array];
    }
    return _visibleResult;
}

- (NSArray *)searchRecords {
    if (!_searchRecords) {
        _searchRecords = [JMSearchRecord searchRecord];
    }
    return _searchRecords;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = JMColor(242, 242, 242);
    
    // 设置导航栏左侧内容
    UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 16, 45);
    [btn setImage:[UIImage imageNamed:@"Backs"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"Back按下@2"] forState:UIControlStateHighlighted];
    [btn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(search)];
    
    // 添加搜索框
    float searchViewRatio = 450.0/75.0;
    UIImageView *searchView = [[UIImageView alloc] init];
    searchView.userInteractionEnabled = YES;
    searchView.width = 200;
    searchView.height = searchView.width/searchViewRatio;
    searchView.image = [UIImage imageNamed:@"searchbg"];
    self.navigationItem.titleView = searchView;
    
    UITextField *searchbar = [[UITextField alloc] init];
    [searchView addSubview:searchbar];
    searchbar.placeholder = @"搜索电动门品牌/型号";
    searchbar.textAlignment = NSTextAlignmentLeft;
    searchbar.font = [UIFont systemFontOfSize:12];
    searchbar.frame = CGRectMake(30, 0, searchView.width - 30, searchView.height);
    [searchView addSubview:searchbar];
    self.searchbar = searchbar;
    
    // 监听searbar的改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchBarDidChange:) name:UITextFieldTextDidChangeNotification object:self.searchbar];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchBarBeginEnditing:) name:UITextFieldTextDidBeginEditingNotification object:self.searchbar];
    
    // 设置tableView
    UITableView *tableVIew = [[UITableView alloc] init];
    self.tableView = tableVIew;
    [self.view addSubview:tableVIew];
    tableVIew.frame = CGRectMake(0, 10, JMPhoneWidth, JMPhoneHeight);
    tableVIew.showsVerticalScrollIndicator = NO;
    tableVIew.dataSource = self;
    tableVIew.delegate = self;
    
    // 去掉多余的cell分割线
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    [tableVIew setTableFooterView:view];
}

/**
 *  返回上一层
 */
- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}


/**
 *  搜索
 */
- (void)search {
    WDLog(@"搜索");
}

/**
 *  监听searchbar的改变,刷新表格
 *
 *  @param notification 通知
 */
- (void)searchBarDidChange:(NSNotification *)notification {
    NSString *filterStr = self.searchbar.text;
    NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"self contains[c] %@", filterStr];
    self.visibleResult = [self.allResult filteredArrayUsingPredicate:filterPredicate];
 
    // 刷新表格
    [self.tableView reloadData];
}

/**
 *  监听searchbar开始编辑,获取所有的搜索数据
 *
 *  @param notification 通知
 */
- (void)searchBarBeginEnditing:(NSNotification *)notification {
    self.search = YES;
    for (int i = 0; i < self.brandGroup.count; i++) {
        JMBrandGroup *brandGroup = self.brandGroup[i];
        [self.allResult addObject:brandGroup.firstchar];
        for (int j = 0; j < brandGroup.brands.count; j++) {
            JMBrand *brand = brandGroup.brands[j];
            [self.allResult addObject:brand.name];
            for (int k = 0; k < brand.models.count; k++) {
                JMCar *car = brand.models[k];
                [self.allResult addObject:car.name];
            }
        }
    }

}

#pragma mark - tableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.isSearch) { // 搜索状态返回搜索结果
        if (0 == self.visibleResult.count) { // 没有匹配的搜索结果
            return 1;
        } else {
            return self.visibleResult.count;
        }
    }
    return self.searchRecords.count - 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //1 创建可重用cell对象
    static NSString *reuseId = @"car";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseId];
    }
    
    // 去掉cell选中时的背景颜色
    UIView *backView = [[UIView alloc] initWithFrame:cell.frame];
    cell.selectedBackgroundView = backView;
    cell.selectedBackgroundView.backgroundColor = [UIColor clearColor];
    
    //2 给cell内部的子控件赋值
    if (self.search) { // 搜索状态

        if (0 == self.visibleResult.count) { // 无匹配结果
            cell.textLabel.text = @"没有匹配结果";
        } else {
            NSString *carType = [NSString stringWithFormat:@"%@", self.visibleResult[indexPath.row]];
            cell.textLabel.text = carType;
        }
        
    } else { // 历史记录
        cell.textLabel.text = [NSString stringWithFormat:@"%@", self.searchRecords[indexPath.row + 1]];
    }
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (!self.search) {
        UIView *customView = [[UIView alloc] init];
        UILabel *label = [[UILabel alloc] init];
        label.opaque = NO;
        //label.textAlignment = NSTextAlignmentCenter;
        label.textColor = JMColor(87, 166, 212);
        label.frame = CGRectMake(15, 0, 100, 20);
        if (self.searchRecords.count > 1) { // 有搜索记录
            label.text = @"历史搜索";
        } else {
            label.text = @"无历史记录";
        }
        
        [customView addSubview:label];
        return customView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (!self.search) { // 历史记录状态
        return 20;
    }
    return 0;
}

/**
 *  获得搜索的文字，并保存
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.search) {
        self.search = !self.search;
        // 跳转选择的详情页
        JMKeyInforController *keyInforVC = [[JMKeyInforController alloc] init];
        keyInforVC.title = self.visibleResult[indexPath.row];
        [self.navigationController pushViewController:keyInforVC animated:YES];
    } else {
        JMKeyInforController *keyInforVC = [[JMKeyInforController alloc] init];
        keyInforVC.title = self.searchRecords[indexPath.row + 1];
        [self.navigationController pushViewController:keyInforVC animated:YES];
    }
    
    // 获得沙盒路径
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [documentPath stringByAppendingPathComponent:@"历史搜索.text"];
    
    // 获得点击处的cell的文字
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
    // 判断以前的数据是否有本次搜索的字符
    for (long i = self.searchRecords.count - 1; i >0; i--) {
        NSString *previousStr = [NSString stringWithFormat:@"%@", self.searchRecords[i]];
        if ([previousStr isEqualToString:cell.textLabel.text]) { // 本次搜索内容已经存在
            return;
        }
    }
    
    // 搜索的字符串前添加空格
    NSString *dataStr = [NSString stringWithFormat:@" %@", cell.textLabel.text];
    NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
    
    //创建数据缓冲
    NSMutableData *writer = [[NSMutableData alloc] init];
    //将字符串添加到缓冲中
    [writer appendData:data];
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    [fileHandle seekToEndOfFile];
    [fileHandle writeData:writer];
    [fileHandle closeFile];
    
    // 回退键盘
    [self.searchbar resignFirstResponder];
    self.search = NO;
    [self.tableView reloadData];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
